﻿# ------------------------ #
# SQL Server Configuration #
# ------------------------ #
param([string]$virtualMachineService, [string]$virtualMachineName)

# Return admin account list
function Get-AdminAccounts($admins)
{
	$result = "";
	foreach ($admin in $admins.admin)
	{
		$result += "`"$($admin.userName)`" "
	}
	return $result
}

# Return SQL Server version number
function Get-SqlServerVersionNumber($version)
{
    switch ($version)
    {
        "2012"
        {
            return "110"
        }
        "2014"
        {
            return "120"
        }
        default
        {
            throw "SQL Server version '$version' is not supported."
        }
    }
}

Write-Information "Virtual machine '$virtualMachineName' executing SQL Server '$($script.type)' configuration ... " -NoNewLine $true
$userName = $subscription.virtualMachines.adminUserName
$password = $subscription.virtualMachines.password
$netBiosDomain = $subscription.virtualMachines.netBiosDomain
$uri = Get-AzureWinRMUri -ServiceName $virtualMachineService -Name $virtualMachineName
$credential = New-Object System.Management.Automation.PSCredential(($netBiosDomain + "\" + $userName), (ConvertTo-SecureString $password -AsPlainText -Force))
$session = New-PSSession -ComputerName $uri[0].DnsSafeHost -Credential $credential -Port (Get-VirtualMachineInstanceEndpointPort $subscription $virtualMachineName) -UseSSL -Authentication Credssp
switch ($script.type)
{
	"Prepare"
	{
		Invoke-Command -Session $session -ScriptBlock {
			Import-Module ServerManager
			$result = Add-WindowsFeature Net-Framework-Features -Source W:\sources\sxs -WarningAction Ignore
			if (!$? -or $result.Success -eq $false) { throw ".NET Framework 3.5 deployment failed." }
		}
	}
	"Install"
	{
		$installed = Invoke-Command -Session $session -ScriptBlock {
			param([string]$sqlVersionNumber)
            if (Test-Path -LiteralPath "$env:ProgramFiles\Microsoft SQL Server\$sqlVersionNumber\Setup Bootstrap\Log\Summary.txt")
            {
                return ((Get-Content "$env:ProgramFiles\Microsoft SQL Server\$sqlVersionNumber\Setup Bootstrap\Log\Summary.txt" | ? {$_ -match "Final result:" -and $_ -match "Passed"}) -ne $null)
            }
            return $false
		} -ArgumentList (Get-SqlServerVersionNumber $script.version)
        if ($installed)
        {
            Remove-PSSession $session
            Write-Text "skipped."
            return
        }
		$admins = Get-AdminAccounts $script.admins
		$parameters = @("/ConfigurationFile=C:\SQL_Server.ini", "/IACCEPTSQLSERVERLICENSETERMS", "/FEATURES=$($script.features)")
		if (![String]::IsNullOrWhiteSpace($script.userName))
		{
			$parameters += "/SQLSVCACCOUNT=`"$($script.userName)`""
			$parameters += "/ASSVCACCOUNT=`"$($script.userName)`""
			$parameters += "/RSSVCACCOUNT=`"$($script.userName)`""
			$parameters += "/AGTSVCACCOUNT=`"$($script.userName)`""
		}
		if (![String]::IsNullOrWhiteSpace($script.password))
		{
			$parameters += "/SQLSVCPASSWORD=`"$($script.password)`""
			$parameters += "/ASSVCPASSWORD=`"$($script.password)`""
			$parameters += "/RSSVCPASSWORD=`"$($script.password)`""
			$parameters += "/AGTSVCPASSWORD=`"$($script.password)`""
		}
		if (![String]::IsNullOrWhiteSpace($admins))
		{
			$parameters += "/SQLSYSADMINACCOUNTS=$admins"
			$parameters += "/ASSYSADMINACCOUNTS=$admins"
		}
		Send-RemoteFile -Source "$env:dp0\Files\$($script.configuration)" -Destination "C:\SQL_Server.ini" -Session $session
		Invoke-Command -Session $session -ScriptBlock {
			param([string[]]$parameters)
            $result = Start-Process -FilePath "S:\Setup.exe" -ArgumentList $parameters -PassThru -Wait
            if ($result.ExitCode -ne 0)
            {
                throw "SQL Server installation failed. Check 'C:\Program Files\Microsoft SQL Server\$sqlVersionNumber\Setup Bootstrap\Log\Summary.txt' for more details."
            }
			Remove-Item "C:\SQL_Server.ini" -Force
		} -ArgumentList (,$parameters)
	}
	"Script"
	{
		Send-RemoteFile -Source "$env:dp0\Files\$($script.configuration)" -Destination "C:\SQL_Script.sql" -Session $session
		Invoke-Command -Session $session -ScriptBlock {
			Import-Module "SQLPS" -DisableNameChecking
			Invoke-SqlCmd -InputFile "C:\SQL_Script.sql" | Out-Null
			Remove-Item "C:\SQL_Script.sql" -Force
		}
	}
	default
	{
		throw "SQL Server type '$($script.type)' is not supported."
	}
}
Remove-PSSession $session
Write-Text "done."